package cn.lyjuan.first.netty.demo._3_netty3.client;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Client
{
    public static void main(String[] args) throws IOException
    {
        // bootstrap
        final ClientBootstrap strap = new ClientBootstrap();

        // socket channel factory
        Executor boss = Executors.newFixedThreadPool(1);
        Executor worker = Executors.newFixedThreadPool(2);
        strap.setFactory(new NioClientSocketChannelFactory(boss, worker, 1, 2));

        // channel pipeline factory
        strap.setPipelineFactory(new ChannelPipelineFactory()
        {
            public ChannelPipeline getPipeline() throws Exception
            {
                ChannelPipeline pipe = Channels.pipeline();

                pipe.addLast("decoder", new StringDecoder());
                pipe.addLast("encoder", new StringEncoder());
                pipe.addLast("handler", new ClientHandler());

                return pipe;
            }
        });

        // connect
        ChannelFuture future = strap.connect(new InetSocketAddress("localhost", 8000));

        SocketChannel chl = (SocketChannel) future.getChannel();

        // input
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while (true)
        {

            System.out.println("请输入:");
            line = read.readLine();

            if ("quit".equalsIgnoreCase(line))
                break;

            chl.write(line);
        }
    }
}
